#!/bin/bash
set -e

RED="\033[31m"
GREEN="\033[32m"
YELLOW="\033[33m"
BLUE="\033[34m"
BOLD="\033[1m"
RESET="\033[0m"

INSTALL_DIR="/usr/local/frpc"
SERVICE_FILE="/etc/systemd/system/frpc.service"
TIMER_FILE="/etc/systemd/system/frpc-restart.timer"
WRAPPER="/usr/local/bin/frp"
CONFIG_FILE="$INSTALL_DIR/frpc.toml"

print_title() {
    echo -e "${BOLD}${BLUE}"
    echo "========================================="
    echo "         FRPC 客户端安装脚本 - 芙芙云"
    echo "             日期: $(date '+%Y-%m-%d')"
    echo "========================================="
    echo -e "${RESET}"
}

print_step() { echo -e "${YELLOW}[*] $1${RESET}"; }
print_ok()   { echo -e "${GREEN}[✔] $1${RESET}"; }
print_err()  { echo -e "${RED}[✖] $1${RESET}"; }

download_with_progress() {
    local url="$1"
    local output="$2"
    
    print_step "开始下载..."
    echo -e "${BLUE}下载链接: ${url}${RESET}"
    
    local file_size_bytes=$(curl -sI "$url" | grep -i 'content-length' | awk '{print $2}' | tr -d '\r' | tail -1)
    local file_size_display="未知"
    
    if [ -n "$file_size_bytes" ] && [ "$file_size_bytes" -gt 0 ]; then
        if [ "$file_size_bytes" -gt 1048576 ]; then
            file_size_mb=$((file_size_bytes / 1048576))
            file_size_remainder=$(( (file_size_bytes % 1048576) / 10485 ))
            file_size_display="${file_size_mb}.${file_size_remainder}MB"
        elif [ "$file_size_bytes" -gt 1024 ]; then
            file_size_kb=$((file_size_bytes / 1024))
            file_size_display="${file_size_kb}KB"
        else
            file_size_display="${file_size_bytes}字节"
        fi
    fi
    
    echo -e "${YELLOW}文件大小: ${file_size_display}${RESET}"
    echo
    
    if command -v pv >/dev/null 2>&1 && [ -n "$file_size_bytes" ] && [ "$file_size_bytes" -gt 0 ]; then
        print_step "使用 pv 显示下载进度..."
        curl -L "$url" | pv -s "$file_size_bytes" -N "下载进度" > "$output"
    else
        print_step "使用 curl 进度条..."
        curl -L --progress-bar -o "$output" "$url"
    fi
    
    if [ $? -eq 0 ] && [ -s "$output" ]; then
        print_ok "下载完成"
        local actual_size=$(du -h "$output" | cut -f1)
        echo -e "${GREEN}实际下载大小: ${actual_size}${RESET}"
    else
        print_err "下载失败"
        return 1
    fi
}

print_title

if [ "$EUID" -ne 0 ]; then
    print_err "请使用 root 用户运行脚本"
    exit 1
fi

print_step "检查并安装依赖..."
if [ -f /etc/debian_version ]; then
    apt-get update -y
    apt-get install -y wget curl tar nano
elif [ -f /etc/centos-release ]; then
    yum install -y wget curl tar nano
elif [ -f /etc/arch-release ]; then
    pacman -Sy --noconfirm wget curl tar nano
else
    print_err "不支持的系统"
    exit 1
fi
print_ok "依赖检查完成"

echo -e "${BOLD}请选择下载源:${RESET}"
echo "  1) GitHub 官方"
echo "  2) 中国加速镜像 (https://gh-proxy.com/)"
read -p "输入选项 [1/2]: " SOURCE_CHOICE
PROXY_PREFIX=""
if [[ "$SOURCE_CHOICE" == "2" ]]; then
    PROXY_PREFIX="https://gh-proxy.com/"
fi

print_step "获取 FRP 最新版本..."
LATEST_VERSION=$(curl -s https://api.github.com/repos/fatedier/frp/releases/latest \
  | grep '"tag_name":' \
  | sed -E 's/.*"v([^"]+)".*/\1/' \
  | head -n 1)
if [ -z "$LATEST_VERSION" ]; then
    print_err "无法获取最新版本，使用备用版本 0.60.0"
    LATEST_VERSION="0.60.0"
fi
print_ok "最新版本: $LATEST_VERSION"

ARCH=$(uname -m)
case "$ARCH" in
    x86_64) FRPC_FILE="frp_${LATEST_VERSION}_linux_amd64.tar.gz" ;;
    aarch64) FRPC_FILE="frp_${LATEST_VERSION}_linux_arm64.tar.gz" ;;
    armv7l) FRPC_FILE="frp_${LATEST_VERSION}_linux_arm.tar.gz" ;;
    *) print_err "不支持的架构: $ARCH"; exit 1 ;;
esac

DOWNLOAD_URL="${PROXY_PREFIX}https://github.com/fatedier/frp/releases/download/v${LATEST_VERSION}/$FRPC_FILE"

download_with_progress "$DOWNLOAD_URL" "/tmp/frpc.tar.gz"

print_step "解压文件..."
mkdir -p $INSTALL_DIR
tar -xzf /tmp/frpc.tar.gz -C /tmp
cp /tmp/frp_${LATEST_VERSION}_linux_*/frpc $INSTALL_DIR/
[ -f /tmp/frp_${LATEST_VERSION}_linux_*/frpc.toml ] && cp /tmp/frp_${LATEST_VERSION}_linux_*/frpc.toml $INSTALL_DIR/
rm -rf /tmp/frp_${LATEST_VERSION}_linux_* /tmp/frpc.tar.gz
print_ok "安装完成"

if [ ! -f "$CONFIG_FILE" ]; then
print_step "生成默认配置文件..."
cat > "$CONFIG_FILE" <<EOF
serverAddr = "1.2.3.4"
serverPort = 7000

[[proxies]]
name = "ssh"
type = "tcp"
localIP = "127.0.0.1"
localPort = 22
remotePort = 6000
EOF
print_ok "配置文件生成完成: $CONFIG_FILE"
fi

print_step "配置 systemd 服务..."
cat > "$SERVICE_FILE" <<EOF
[Unit]
Description=FRPC Service
After=network.target

[Service]
ExecStart=$INSTALL_DIR/frpc -c $CONFIG_FILE
Restart=always
User=root

[Install]
WantedBy=multi-user.target
EOF
systemctl daemon-reload
systemctl enable frpc
print_ok "systemd 服务配置完成"

print_step "配置自动重启定时器..."
cat > "/etc/systemd/system/frpc-restart.service" <<EOF
[Unit]
Description=FRPC Restart Service
After=frpc.service

[Service]
ExecStart=/usr/local/frpc/frpc -c /usr/local/frpc/frpc.toml
Restart=always
User=root
EOF

cat > "$TIMER_FILE" <<EOF
[Unit]
Description=FRPC Auto Restart Timer
Requires=frpc-restart.service

[Timer]
OnCalendar=*-*-* 03:00:00
Persistent=true

[Install]
WantedBy=timers.target
EOF
systemctl daemon-reload
systemctl enable frpc-restart.timer
print_ok "自动重启定时器配置完成"

print_step "创建管理命令 frp ..."
cat > "$WRAPPER" <<'EOF'
#!/bin/bash
SERVICE_NAME=frpc
CONFIG_FILE=/usr/local/frpc/frpc.toml
BIN_FILE=/usr/local/frpc/frpc
RESTART_TIME_FILE=/usr/local/frpc/restart_time

print_step() { echo -e "\033[33m[*] $1\033[0m"; }
print_ok()   { echo -e "\033[32m[✔] $1\033[0m"; }
print_err()  { echo -e "\033[31m[✖] $1\033[0m"; }

interactive_config() {
    echo -e "\n🛠 交互式配置 frpc.toml"
    read -p "请输入 FRP 服务端 IP: " SERVER_ADDR
    read -p "请输入 FRP 服务端端口 (默认 7000): " SERVER_PORT
    SERVER_PORT=${SERVER_PORT:-7000}
    read -p "请输入 FRP Token（可选）: " TOKEN
    read -p "请输入本地服务 IP (默认 127.0.0.1): " LOCAL_IP
    LOCAL_IP=${LOCAL_IP:-127.0.0.1}
    read -p "请输入映射端口范围 (示例 50000-50002): " PORT_RANGE
    read -p "请输入协议类型 tcp/udp (默认 tcp): " PROTOCOL
    PROTOCOL=${PROTOCOL:-tcp}

    echo -e "\n⚙️ 生成配置文件..."
    cat > "$CONFIG_FILE" <<EOF2
serverAddr = "${SERVER_ADDR}"
serverPort = ${SERVER_PORT}
$( [ -n "$TOKEN" ] && echo "token = \"${TOKEN}\"" )
logFile = "./frpc.log"
logLevel = "info"
logMaxDays = 3
EOF2

    IFS='-' read -r START_PORT END_PORT <<< "$PORT_RANGE"
    for ((port=START_PORT; port<=END_PORT; port++)); do
    cat >> "$CONFIG_FILE" <<EOF2

[[proxies]]
name = "port_${port}"
type = "${PROTOCOL}"
localIP = "${LOCAL_IP}"
localPort = ${port}
remotePort = ${port}
EOF2
    done
    print_ok "配置文件生成完成: $CONFIG_FILE"
}

set_auto_restart() {
    local hours=$1
    if [[ -z "$hours" ]] || [[ "$hours" -lt 1 ]]; then
        print_err "请提供有效的重启时间（小时数），例如：frp -time 24"
        return 1
    fi
    
    print_step "设置 FRPC 每 ${hours} 小时自动重启..."
    
    echo "$hours" > "$RESTART_TIME_FILE"
    
    cat > "/etc/systemd/system/frpc-restart.service" <<EOF2
[Unit]
Description=FRPC Restart Service
After=frpc.service

[Service]
Type=oneshot
ExecStart=/bin/systemctl restart frpc
User=root
EOF2

    cat > "/etc/systemd/system/frpc-restart.timer" <<EOF2
[Unit]
Description=FRPC Auto Restart Timer (every ${hours} hours)
Requires=frpc-restart.service

[Timer]
OnBootSec=${hours}h
OnUnitActiveSec=${hours}h
Persistent=true

[Install]
WantedBy=timers.target
EOF2

    systemctl daemon-reload
    systemctl enable frpc-restart.timer
    systemctl start frpc-restart.timer
    
    if systemctl is-active frpc-restart.timer >/dev/null 2>&1; then
        print_ok "已设置 FRPC 每 ${hours} 小时自动重启"
        echo -e "定时器状态: systemctl status frpc-restart.timer"
    else
        print_err "定时器启动失败，请检查日志: journalctl -u frpc-restart.timer"
        return 1
    fi
}

disable_auto_restart() {
    print_step "禁用 FRPC 自动重启..."
    systemctl stop frpc-restart.timer 2>/dev/null || true
    systemctl disable frpc-restart.timer 2>/dev/null || true
    systemctl stop frpc-restart.service 2>/dev/null || true
    systemctl disable frpc-restart.service 2>/dev/null || true
    rm -f "$RESTART_TIME_FILE" 2>/dev/null || true
    rm -f "/etc/systemd/system/frpc-restart.service" 2>/dev/null || true
    rm -f "/etc/systemd/system/frpc-restart.timer" 2>/dev/null || true
    systemctl daemon-reload
    print_ok "已禁用 FRPC 自动重启"
}

show_restart_status() {
    if systemctl is-active frpc-restart.timer >/dev/null 2>&1; then
        if [[ -f "$RESTART_TIME_FILE" ]]; then
            local hours=$(cat "$RESTART_TIME_FILE")
            print_ok "FRPC 自动重启已启用，每 ${hours} 小时重启一次"
        else
            print_ok "FRPC 自动重启已启用（默认每天 03:00 重启）"
        fi
        
        local next_time=$(systemctl list-timers frpc-restart.timer --no-pager 2>/dev/null | grep frpc-restart | head -1 | awk '{print $1, $2, $3, $4, $5}')
        if [ -n "$next_time" ]; then
            echo -e "下次重启时间: ${next_time}"
        fi
    else
        print_err "FRPC 自动重启未启用"
    fi
}

case "$1" in
  -s) systemctl start $SERVICE_NAME ;;
  -t) systemctl stop $SERVICE_NAME ;;
  -r) systemctl restart $SERVICE_NAME ;;
  -S) systemctl status $SERVICE_NAME --no-pager ;;
  -c) ${EDITOR:-nano} $CONFIG_FILE ;;
  -v) $BIN_FILE -v ;;
  -i) interactive_config ;;
  -time)
    if [[ "$2" == "disable" ]]; then
        disable_auto_restart
    elif [[ -n "$2" ]]; then
        set_auto_restart "$2"
    else
        show_restart_status
    fi
    ;;
  *)
    echo -e "  frp -s        启动 FRP"
    echo -e "  frp -t        停止 FRP"
    echo -e "  frp -r        重启 FRP"
    echo -e "  frp -S        查看状态"
    echo -e "  frp -c        编辑配置文件"
    echo -e "  frp -v        查看版本"
    echo -e "  frp -i        交互式配置 frpc.toml"
    echo -e "  frp -time <小时数>  设置自动重启间隔"
    echo -e "  frp -time disable   禁用自动重启"
    echo -e "  frp -time           查看自动重启状态"
    exit 1
    ;;
esac
EOF
chmod +x "$WRAPPER"
print_ok "frp 管理命令创建完成"

echo -e "\n${GREEN}${BOLD}安装完成！${RESET}"
echo -e "使用命令管理 frpc:"
echo -e "  frp -s        启动 FRP"
echo -e "  frp -t        停止 FRP"
echo -e "  frp -r        重启 FRP"
echo -e "  frp -S        查看状态"
echo -e "  frp -c        编辑配置文件"
echo -e "  frp -v        查看版本"
echo -e "  frp -i        交互式配置 frpc.toml"
echo -e "  frp -time <小时数>  设置自动重启间隔"
echo -e "  frp -time disable   禁用自动重启"
echo -e "  frp -time           查看自动重启状态"
echo -e "\n${YELLOW}默认已启用每天03:00自动重启，可使用 'frp -time 24' 改为每24小时重启${RESET}"